
// http请求
function httpRequest(paramObj, fun, errFun) {
    let xmlhttp = null;
    /*创建XMLHttpRequest对象，
     *老版本的 Internet Explorer（IE5 和 IE6）使用 ActiveX 对象：new ActiveXObject("Microsoft.XMLHTTP")
     * */
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    /*判断是否支持请求*/
    if (xmlhttp == null) {
        alert('你的浏览器不支持XMLHttp');
        return;
    }
    /*请求方式，并且转换为大写*/
    let httpType = (paramObj.requestType || 'GET').toUpperCase();
    /*数据类型*/
    let dataType = paramObj.dataType || 'json';
    /*请求接口*/
    let httpUrl = paramObj.httpUrl || '';
    /*是否异步请求*/
    let async = paramObj.async || true;
    /*请求参数--post请求参数格式为：foo=bar&lorem=ipsum*/
    let paramData = paramObj.data || [];
    let requestData = '';
    for (let name in paramData) {
        requestData += name + '=' + paramData[name] + '&';
    }
    // 去掉末尾的&
    requestData = requestData == '' ? '' : requestData.substring(0, requestData.length - 1);

    /*请求接收*/
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            /*成功回调函数*/
            fun(xmlhttp.responseText);
            // 返回请求返回的数据
            return xmlhttp.responseText;
        } else {
            /*失败回调函数*/
            errFun;
        }
    }

    /*接口连接，先判断连接类型是post还是get*/
    if (httpType == 'GET') {
        xmlhttp.open("GET", httpUrl, async);
        xmlhttp.send(null);
    } else if (httpType == 'POST') {
        xmlhttp.open("POST", httpUrl, async);
        //发送合适的请求头信息
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.send(requestData);
    }
}

// http请求另一种方式
// https://www.cnblogs.com/everlose/p/12501202.html
function ajax(opts) {
    let xhr = new XMLHttpRequest(),
        type = opts.type || 'GET',
        url = opts.url,
        params = opts.data,
        dataType = opts.dataType || 'json';

    type = type.toUpperCase();

    if (type === 'GET') {
        // 将参数拼接到url后
        params = (function (obj) {
            let str = '';

            for (let prop in obj) {
                str += prop + '=' + obj[prop] + '&'
            }
            str = str.slice(0, str.length - 1);
            return str;
        })(opts.data);
        // 如果有额外参数，则补全url
        if(params != "") {
            url += url.indexOf('?') === -1 ? '?' + params : '&' + params;
        }
    }

    xhr.open(type, url);

    if (opts.contentType) {
        xhr.setRequestHeader('Content-type', opts.contentType);
    }

    xhr.send(params ? params : null);

    //return promise
    return new Promise(function (resolve, reject) {
        // xhr.onload - 请求成功回调函数
        //please use 'onreadystatechange' if need support IE9-
        xhr.onload = function () {
            if (xhr.status === 200) {
                let result;
                try {
                    result = JSON.parse(xhr.response);
                } catch (e) {
                    result = xhr.response;
                }
                resolve(result);
            } else {
                reject(xhr.response);
            }
        };

    });
}

